package com.orkhonsoft.tengrinshar.chat.controller;


import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;

import com.orkhonsoft.tengrinshar.chat.service.UserService;
import org.apache.logging.log4j.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.orkhonsoft.tengrinshar.chat.common.UserException;
import com.orkhonsoft.tengrinshar.chat.common.UserException.Type;
import com.orkhonsoft.tengrinshar.chat.entity.UserEntity;
import com.orkhonsoft.tengrinshar.chat.utils.JwtHelper;


/**
 * Controller公共组件
 */
public abstract class AbstractController {
    protected Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private UserService userService;

    protected UserEntity getUsers() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String token = request.getHeader("token");
        Map<String, String> map = null;
        try {
            map = JwtHelper.verifyToken(token);
        } catch (Exception e) {
            throw new UserException(Type.USER_NOT_LOGIN, "User not login");
        }
        UserEntity user = userService.queryObject(map.get("userid"));
        userService.refreshToken(user, token);
        return user;
    }
    
    protected String getToken() {
		ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = requestAttributes.getRequest();
		String token=request.getHeader("token");
	    return token;
	}

    protected Long getUserId() {
        return getUsers().getId();
    }
}
